<?php
namespace app\common\service;

use app\common\util\Upload;
use app\common\util\Util;
use think\Model;
use think\Request;

class MaterialService extends BaseService
{

    /**
     * @param $sid
     * @param $type 获取类型 0：获取所有；1：单图文；2：多图文；
     * @return array
     * 获取素材库列表
     */
    public function getMateriaList($sid, $type){
        $where['sid'] = $sid;
        $where['status'] = 1;
        if($type > 0){
            $where['type'] = $type;
        }
        $list_count = db('res')->where($where)->count();
        $list = db('res')->where($where)->order('create_time DESC')->select();

        $data = [];
        if($list){
            foreach($list as $k => $v){
                $res_temp = $v['res'];
                $res_temp = str_replace(PHP_EOL, "", $res_temp);
                $temp = json_decode($res_temp, true);
                $data[$k] = [
                    'res_id' => $v['res_id'],
                    'title' => $temp['title'],
                    'create_time' => date('Y-m-d H:i:s', $v['create_time']),
                    'coverimg' => $temp['coverimg'],
                    'summary' => $temp['summary'] ?? '',
                    'type' => $v['type'],
                    'dataset' => $temp['dataset'] ?? '',
                ];
            }
        }
        return ['content' => $data,'page' =>['count' =>$list_count]];
    }

    /**
     * @param $sid
     * @param int $res_id
     * @param array $postParam
     * @return int|string
     * 新增或修改单图文
     */
    public function editMaterialOne($sid, $res_id = 0, $postParam = []){
        $data['title'] = urlencode($postParam['title']);
        $data['link_id'] = urlencode($postParam['link_id'] ?? 0);
        $data['link_type'] = urlencode($postParam['link_type'] ?? 0);
        $data['link_name'] = urlencode($postParam['link_name'] ?? '');
        $data['redirect'] = urlencode($postParam['redirect'] ?? '');
        $data['coverimg'] = urlencode($postParam['coverimg']);
        $data['datetime'] = null;
        $data['summary'] = urlencode($postParam['summary'] ?? '');
        $data['content'] = $postParam['content'] ? urlencode(addslashes($postParam['content'])) : '';

        if($res_id == 0){
            //新增
            $result = $this->addMaterial($sid, $data, 1);
        } else {
            //更新
            $result = $this->updateMaterial($sid, $res_id, $data);
        }
        return $result;
    }

    /**
     * @param $sid
     * @param $res
     * @param $type 图文类型 1：单图文  2：多图文
     * @return int|string
     * 新增图文
     */
    public function addMaterial($sid, $res, $type){
        $res_temp = urldecode(json_encode($res));
        $res_temp = str_replace(PHP_EOL, "", $res_temp);
        $data = [
            'sid' => $sid,
            'res' => $res_temp,
            'create_time' => time(),
            'type' => $type,
            'status' => 1
        ];
        return db('res')->insert($data);
    }

    /**
     * @param $sid
     * @param $res_id
     * @param $res
     * @return int|string
     * @throws \think\Exception
     * 更新图文
     */
    public function updateMaterial($sid, $res_id, $res){
        $res_temp = urldecode(json_encode($res));
        $res_temp = str_replace(PHP_EOL, "", $res_temp);
        $where = [
            'res_id' => $res_id,
            'sid' => $sid
        ];
        $data = [
            'res' => $res_temp,
            'create_time' => time()
        ];
        return db('res')->where($where)->update($data);
    }

    /**
     * @param $sid
     * @param $res_id
     * @return int
     * 软删除图文
     */
    public function softDeleteMaterial($sid, $res_id){
        return db('res')->where(['sid' => $sid, 'res_id' => $res_id])->setField('status', -1);
    }

    /**
     * @param $sid
     * @param int $res_id
     * @param array $postParam
     * @return int|string
     * 新增或更新多图文
     */
    public function editMaterialMore($sid, $res_id = 0, $postParam = []){
        $data['title'] = urlencode($postParam['title']);
        $data['link_id'] = urlencode($postParam['link_id'] ?? 0);
        $data['link_type'] = urlencode($postParam['link_type'] ?? 0);
        $data['link_name'] = urlencode($postParam['link_name'] ?? '');
        $data['redirect'] = urlencode($postParam['redirect'] ?? '');
        $data['coverimg'] = urlencode($postParam['coverimg']);
        $dataset = $postParam['dataset'];
        foreach ($dataset as $k => $v) {
            $data['dataset'][] = [
                'material_more_id' => 0,
                'seller_id' => $sid,
                'group_id' => 0,
                'is_main' => 0,
                'title' => urlencode($v['title']),
                'cover_img' => urlencode($v['img']),
                'redirect' => urlencode($v['redirect'] ?? ''),
                'add_time' => time(),
                'link_type' => urlencode($v['link_type'] ?? 0),
                'link_id' => urlencode($v['link_id'] ?? 0),
                'link_name' => urlencode($v['link_name'] ?? ''),
                'error_id' => urlencode($v['error_id'] ?? 0),
                'img' => urlencode($v['img']),
                'content' => $v['content'] ? urlencode(addslashes($v['content'])) : '',
            ];
        }

        $data['content'] = urlencode(addslashes($postParam['content']));
//        $data['content'] = urlencode(str_replace('"',"'",$postParam['content']));
//        $data['content'] = urlencode(str_replace('"','\"',$postParam['content']));

        if($res_id == 0){
            //新增
            $result = $this->addMaterial($sid, $data, 2);
        } else {
            //更新
            $result = $this->updateMaterial($sid, $res_id, $data);
        }
        return $result;
    }

    /**
     * @param $sid
     * @param $res_id
     * @return array
     * 获取图文详情
     */
    public function getMaterialDetail($sid, $res_id){
        $detail = db('res')->where(['sid' => $sid, 'res_id' => $res_id])->find();

        if(!$detail){
            return false;
        }
        $res_temp = $detail['res'];
        $res_temp = str_replace(PHP_EOL, "", $res_temp);
        $temp = json_decode($res_temp, true);
        $data = [
            'res_id' => $detail['res_id'],
            'title' => $temp['title'],
            'create_time' => date('Y-m-d H:i:s', $detail['create_time']),
            'coverimg' => $temp['coverimg'],
            'summary' => $temp['summary'] ?? '',
//            'content' => strip_tags(htmlspecialchars_decode($temp['content'])),
            'content' => htmlspecialchars_decode($temp['content']),
            'type' => $detail['type'],
            'dataset' => $temp['dataset'] ?? '',
//            'link' => $temp['link'] ?? $temp['redirect'],
            'redirect' => $temp['redirect']
        ];
        return ['content' => $data];
    }

    /**
     * 图文上传
     * @param $sid
     * @param $res_id
     * @return array|mixed|string
     */
    public function uploadMaterial($sid, $res_id){
        $res = db('res')->where(['sid' => $sid, 'res_id' => $res_id])->find();
        if(empty($res)){
            return ['status' => 0, 'msg' => '图文选择错误'];
        }

        $res_content = json_decode($res['res'], true);

        //用正则表达式匹配出字符串中所有的img src，上传到微信服务器，并将URL替换
        $html = (str_replace("\"", "'", html_entity_decode($res_content['content'])));

        $wxService = new WeixinService();

        //替换图文内容中的图片地址
        $res_content['content'] = $wxService->replace_material_image($sid, $html);

        //上传缩略图
        //$cover_img = __DIR__.'/../../../runtime'.$res_content['coverimg'];
        if (preg_match('/^http:/', $res_content['coverimg']) == 0) {

            $cover_img = __DIR__.'/../../../runtime'.$res_content['coverimg'];
        }
        else
        {
            $cover_img = $res_content['coverimg'];
            $file_name = __DIR__.'/../../../runtime/file_temp/'.time().'.png';

            \app\common\helper\BaseHelper::httpcopy($cover_img,$file_name);

            $cover_img = $file_name;

        }
        $thumb_media_id = $wxService->upload_material_thumb($sid, $cover_img);

        //保存图文数据
        $article = [];
        $article[0] = [
            'title' => $res_content['title'],
            'author' => 'admin',
            'thumb_media_id' => $thumb_media_id,
            'content_source_url' => $res_content['redirect'] ?? '',
            'content' =>  $res_content['content'],
            'digest' => $res_content['summary'] ?? '',
            'show_cover_pic' => '1'
        ];

        //多图文数据处理
        if($res['type'] == 2){
            if(isset($res_content['dataset'])){
                foreach($res_content['dataset'] as $k => $v){
                    $cover_img_more = __DIR__.'/../../../runtime'.$v['cover_img'];
                    $thumb_media_id_more = $wxService->upload_material_thumb($sid, $cover_img_more);
                    $article[$k+1] = [
                        'title' => $v['title'],
                        'author' => 'admin',
                        'thumb_media_id' => $thumb_media_id_more,
                        'content_source_url' => $v['redirect'] ?? '',
                        'content' =>  $v['content'],
                        'digest' => $v['summary'] ?? '',
                        'show_cover_pic' => '0'
                    ];
                }
            }
        }

        //上传图文
        $result = $wxService->upload_material($sid, $article);

        $result = json_decode($result,1);

        //上传报错
        if(isset($result['errcode']) && $result['errcode'] > 0){
            $upload_err = Util::get_error($result['errcode']);
            return ['status' => 0, 'msg' => $result['errcode'] . ':' . $upload_err];
        }

        return $result;
    }


    /**
     * 上传图文封面图
     * @return array|string
     */
    public function uploadFile(){
        $result = Upload::uploadFile();
        if($result == false){
            return ['status'=> 0, 'msg'=>'上传失败', 'data' => ''];
        }

        $img_url = Util::qiniu_url($result);

        $thumb_img_url = Util::small_qiniu_url($img_url);

        $data['img_url'] = $thumb_img_url;
        return ['content' => $data];
    }
}







